<template>
    <main-page>
        <data-table ref="dataTableRef" :columns="columns" :expand-row-keys="['1']" :params="params" :pagination="false" api="/dept">
            <template #button>
                <el-button v-auth="'dept:add'" @click="onEdit()"></el-button>
            </template>
            <template #search>
                <el-form-item label="部门名称" prop="deptName">
                    <el-input v-model="params.deptName"/>
                </el-form-item>
            </template>
        </data-table>

        <!-- 新增 / 修改 -->
        <edit ref="editRef"/>
    </main-page>
</template>

<script lang="ts" setup>
import {ref} from "vue";
import DataTable from '@/components/data-table/index.vue';
import Edit from './edit.vue';
import {service} from "@/utils";

const dataTableRef = ref();
const editRef = ref<InstanceType<typeof Edit>>();
const params = ref({
    deptName: undefined
})
const columns = ref([
    {prop: 'name', label: '部门名称', width: 400, search: {prop: 'deptName'}},
    {prop: 'order', label: '排列序号'},
    {prop: 'createTime', label: '创建时间'},
    {prop: 'modifyTime', label: '修改时间'},
    {
        type: "action",
        render: [
            {auth: 'dept:update', onClick: ({row}: any) => onEdit(row)},
            {auth: 'dept:delete', onClick: ({row}: any) => onDelete(row), type: 'danger'}
        ]
    }
])

function onEdit(row?: any) {
    const data = row ? {
        deptId: row.id,
        deptName: row.name,
        parentId: row.pid,
        orderNum: row.order,
    } : null;
    editRef.value?.open({
        data: data,
        confirm: (resolve: (value: any) => void, form: any, operate: AxiosMethod) => {
            service[operate]('/dept', form).then(({code}) => {
                if (code === 200) {
                    dataTableRef.value?.refresh();
                }
                resolve(code);
            })
        }
    })
}

// 删除
function onDelete(row: any) {
    service.confirm(`确定对用户名[${row.name}]进行删除操作,该操作不可逆?`, {
        url: '/dept',
        data: {
            deptIds: [row.id]
        },
        success: dataTableRef.value.refresh
    })
}
</script>
